/**
 * Notes: 注册登录模块业务逻辑 (新版API)
 * Ver : WeCollege Server API 1.0.0
 * Date: 2025-01-27
 * Description: 使用自建服务器API重构登录认证系统
 */

const BaseBiz = require('./base_biz.js');
const cacheHelper = require('../../helper/cache_helper.js');
const serverHelper = require('../../helper/cloud_helper.js'); // 使用替换后的helper
const pageHelper = require('../../helper/page_helper.js');
const helper = require('../../helper/helper.js');
const constants = require('../constants.js');

class PassportBiz extends BaseBiz {

  // 获取用户token
  static getToken() {
    let token = cacheHelper.get(constants.CACHE_TOKEN);
    return token || null;
  }

  // 设置用户token
  static setToken(token) {
    if (!token) return;
    cacheHelper.set(constants.CACHE_TOKEN, token, constants.CACHE_TOKEN_EXPIRE);
  }

  // 获取用户ID
  static getUserId() {
    let token = cacheHelper.get(constants.CACHE_TOKEN);
    if (!token) return '';
    return token.id || token.userId || '';
  }

  // 获取用户名称
  static getUserName() {
    let token = cacheHelper.get(constants.CACHE_TOKEN);
    if (!token) return '';
    return token.name || token.nickName || '';
  }

  // 获取用户头像
  static getUserPic() {
    let token = cacheHelper.get(constants.CACHE_TOKEN);
    if (!token) return '';
    return token.pic || token.image || '';
  }

  // 是否登录
  static isLogin() {
    let id = PassportBiz.getUserId();
    return (id.length > 0) ? true : false;
  }

  // 清除登录缓存
  static clearToken() {
    cacheHelper.remove(constants.CACHE_TOKEN);
  }

  // 静默登录 (必须登录)
  static async loginSilenceMust(that = null) {
    try {
      // 检查本地token
      let token = PassportBiz.getToken();
      if (token && token.id) {
        return true;
      }

      // 获取微信登录code
      const loginRes = await new Promise((resolve, reject) => {
        wx.login({
          success: resolve,
          fail: reject
        });
      });

      if (!loginRes.code) {
        throw new Error('获取微信登录code失败');
      }

      // 调用服务器登录接口
      const result = await serverHelper.callCloudSumbit('passport/login', {
        code: loginRes.code
      }, { title: 'bar' });

      if (result && result.data) {
        // 构建token对象
        const tokenData = {
          id: result.data.user.userId || result.data.user.openId,
          userId: result.data.user.userId,
          openId: result.data.user.openId,
          name: result.data.user.nickName || result.data.user.name,
          pic: result.data.user.image || result.data.user.avatar,
          status: result.data.user.status || 1,
          token: result.data.token
        };

        PassportBiz.setToken(tokenData);
        return true;
      }

      return false;
    } catch (err) {
      console.error('静默登录失败:', err);
      return false;
    }
  }

  // 静默登录 (可选登录)
  static async loginSilence(that = null) {
    try {
      return await PassportBiz.loginSilenceMust(that);
    } catch (err) {
      console.error('静默登录失败:', err);
      return false;
    }
  }

  // 检查登录状态
  static async loginCheck(that = null) {
    let isLogin = await PassportBiz.loginSilenceMust(that);
    if (!isLogin) {
      // 跳转到登录页面
      wx.reLaunch({
        url: pageHelper.fmtURLByPID('/pages/my/login/my_login'),
      });
      return false;
    }
    return true;
  }

  // 用户注册
  static async register(data) {
    try {
      // 获取微信登录code
      const loginRes = await new Promise((resolve, reject) => {
        wx.login({
          success: resolve,
          fail: reject
        });
      });

      if (!loginRes.code) {
        throw new Error('获取微信登录code失败');
      }

      const registerData = {
        code: loginRes.code,
        nickName: data.formName,
        mobile: data.formMobile,
        forms: data.forms || []
      };

      const result = await serverHelper.callCloudSumbit('passport/register', registerData);

      if (result && result.data) {
        // 构建token对象
        const tokenData = {
          id: result.data.user.userId || result.data.user.openId,
          userId: result.data.user.userId,
          openId: result.data.user.openId,
          name: result.data.user.nickName || result.data.user.name,
          pic: result.data.user.image || result.data.user.avatar,
          status: result.data.user.status || 1,
          token: result.data.token
        };

        PassportBiz.setToken(tokenData);
        return tokenData;
      }

      throw new Error(result.message || '注册失败');
    } catch (err) {
      console.error('用户注册失败:', err);
      throw err;
    }
  }

  // 获取用户详情
  static async getMyDetail() {
    if (!PassportBiz.isLogin()) {
      return null;
    }

    try {
      const result = await serverHelper.callCloudData('passport/my_detail', {});
      
      if (result && result.data) {
        // 更新本地token信息
        let token = PassportBiz.getToken();
        if (token) {
          token.name = result.data.nickName || result.data.name || token.name;
          token.pic = result.data.image || result.data.avatar || token.pic;
          token.status = result.data.status || token.status;
          PassportBiz.setToken(token);
        }
        
        return result.data;
      }

      return null;
    } catch (err) {
      console.error('获取用户详情失败:', err);
      return null;
    }
  }

  // 编辑用户基本信息
  static async editBase(data) {
    if (!PassportBiz.isLogin()) {
      throw new Error('请先登录');
    }

    try {
      const updateData = {
        nickName: data.formName,
        mobile: data.formMobile,
        pic: data.formPic,
        forms: data.forms || []
      };

      const result = await serverHelper.callCloudSumbit('passport/edit_base', updateData);

      if (result && result.data) {
        // 更新本地token信息
        let token = PassportBiz.getToken();
        if (token) {
          token.name = updateData.nickName || token.name;
          token.pic = updateData.pic || token.pic;
          PassportBiz.setToken(token);
        }
        
        return result.data;
      }

      throw new Error(result.message || '更新失败');
    } catch (err) {
      console.error('编辑用户信息失败:', err);
      throw err;
    }
  }

  // 获取手机号
  static async getPhone(e) {
    if (!e.detail.encryptedData) {
      throw new Error('获取手机号失败');
    }

    try {
      const result = await serverHelper.callCloudSumbit('passport/phone', {
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv
      });

      if (result && result.data && result.data.mobile) {
        return result.data.mobile;
      }

      throw new Error(result.message || '获取手机号失败');
    } catch (err) {
      console.error('获取手机号失败:', err);
      throw err;
    }
  }

  // 用户退出登录
  static logout() {
    PassportBiz.clearToken();
    wx.reLaunch({
      url: pageHelper.fmtURLByPID('/pages/default/index/default_index'),
    });
  }

  // 检查用户状态
  static checkUserStatus() {
    let token = PassportBiz.getToken();
    if (!token) return false;

    // 检查用户状态
    if (token.status === 0) {
      wx.showModal({
        title: '账号审核中',
        content: '您的账号正在审核中，请耐心等待',
        showCancel: false
      });
      return false;
    }

    if (token.status === 9) {
      wx.showModal({
        title: '账号已禁用',
        content: '您的账号已被禁用，如有疑问请联系管理员',
        showCancel: false,
        success: () => {
          PassportBiz.logout();
        }
      });
      return false;
    }

    return true;
  }

  // 获取用户信息 (兼容旧版本)
  static getUserInfo() {
    let token = PassportBiz.getToken();
    if (!token) return null;

    return {
      USER_ID: token.userId || token.id,
      USER_MINI_OPENID: token.openId || token.id,
      USER_NAME: token.name,
      USER_PIC: token.pic,
      USER_STATUS: token.status
    };
  }

  // 设置用户信息 (兼容旧版本)
  static setUserInfo(userInfo) {
    if (!userInfo) return;

    const tokenData = {
      id: userInfo.USER_MINI_OPENID || userInfo.USER_ID,
      userId: userInfo.USER_ID,
      openId: userInfo.USER_MINI_OPENID,
      name: userInfo.USER_NAME,
      pic: userInfo.USER_PIC,
      status: userInfo.USER_STATUS
    };

    PassportBiz.setToken(tokenData);
  }
}

/** 表单校验 */
PassportBiz.CHECK_FORM = {
  name: 'formName|must|string|min:1|max:30|name=姓名',
  mobile: 'formMobile|must|mobile|name=手机号码'
};

module.exports = PassportBiz;